import axios from "axios";
import { MessageBox, Message } from "element-ui";
import { os } from "@/utils/common.js";
import Cookies from "js-cookie";
const errorCode = {
    401: "认证失败，无法访问系统资源",
    403: "当前操作没有权限",
    404: "访问资源不存在",
    // 500: "系统未知错误，请反馈给管理员",
    default: "系统未知错误，请反馈给管理员",
};

let contentType = {
    formData: "multipart/form-data",
    jsonStr: "application/json",
};
const service = axios.create({
    // baseURL: process.env.NODE_ENV !== 'production' ? '/api' : '/api',
    baseURL: "/api",
    timeout: 100000,
});

// 请求拦截
service.interceptors.request.use(
    (config) => {
        // config.data = JSON.stringify(config.data)
        if (config.methodType == "jsonStr") {
            config.data = JSON.stringify(config.data);
        }
        config.headers["Content-Type"] = contentType[config.methodType];

        if (
            Cookies.get("userInfo") != null &&
            Cookies.get("userInfo").length != 0 &&
            JSON.parse(Cookies.get("userInfo")).token
        ) {
            config.headers["Authorization"] = JSON.parse(
                Cookies.get("userInfo")
            ).token; // 让每个请求携带自定义token 请根据实际情况自行修改
        }

        return config;
    },
    (error) => {
        Promise.reject(error);
    }
);

// 响应拦截
service.interceptors.response.use(
    (res) => {
        const code = res.data.code || 200;
        const msg = errorCode[code] || res.data.msg || errorCode;
        if (code === 10001) {
            MessageBox.confirm(
                "登录状态已过期，您可以继续留在该页面，或者重新登录",
                "系统提示", {
                    confirmButtonText: "重新登录",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).then(() => {
                // 删除cookie中的userInfo值
                Cookies.remove("userInfo");
                // 如果是手机端 去手机端登录页
                if (os.isAndroid || os.isPhone) {
                    location.href = "/mobileLogin?redirect=" + location.pathname;
                    return
                }
                location.href = "/login?redirect=" + location.pathname;
                // store.dispatch('LogOut').then(() => {
                //     location.href = '/index';
                // })
            });
        } else if (code === 500) {
            Message({
                message: msg,
                type: "error",
            });
            return Promise.reject(new Error(msg));
        } else if (code !== 200) {
            Message({
                message: msg,
                type: "error",
            });
            // Notification.error({
            //   title: msg
            // })
            return Promise.reject("error");
        } else {
            return res.data;
        }
    },
    (error) => {
        Message({
            message: error,
            type: "error",
        });
        return Promise.reject(error);
    }
);
export default service;